#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
调试收藏数据
"""

import sys
import os
sys.path.append('backend')

from backend.app import create_app
from backend.app.services.civil_code_service import civil_code_service

def debug_favorites():
    """调试收藏数据"""
    print("调试收藏数据")
    
    app = create_app()
    
    with app.app_context():
        try:
            civil_code_service._init_db()
            
            if civil_code_service.favorites_collection is None:
                print("favorites_collection为None")
                return
            
            # 查看所有收藏数据
            all_favorites = list(civil_code_service.favorites_collection.find({}))
            print(f"数据库中总收藏数: {len(all_favorites)}")
            
            for i, fav in enumerate(all_favorites):
                print(f"收藏 {i+1}: user_id={fav.get('user_id')}, article_number={fav.get('article_number')}, created_at={fav.get('created_at')}")
            
            # 测试不同用户ID的查询
            test_user_ids = ["anonymous", "ip_12ca17b49af2", "test_user"]
            
            for user_id in test_user_ids:
                count = civil_code_service.favorites_collection.count_documents({"user_id": user_id})
                print(f"用户 {user_id} 的收藏数: {count}")
                
                if count > 0:
                    favorites = list(civil_code_service.favorites_collection.find({"user_id": user_id}))
                    for fav in favorites:
                        print(f"  - {fav.get('article_number')} (创建时间: {fav.get('created_at')})")
            
        except Exception as e:
            print(f"调试失败: {e}")
            import traceback
            traceback.print_exc()

if __name__ == "__main__":
    debug_favorites()
